package com.example.fuluchou.common.untils;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;

import java.util.List;
import java.util.concurrent.Callable;

public class JacksonUtil {

    /**
     * 静态代码块单例
     */
    private JacksonUtil() {

    }

    private final static ObjectMapper OBJECT_MAPPER;

    static {
        OBJECT_MAPPER = new ObjectMapper();
    }

    private static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }


    protected static <T> T tryParse(Callable<T> parser) {
        return tryParse(parser, JacksonException.class);
    }

    /**
     *  from  Spirng JacksonJsonParser and tryParse
     * @param parser
     * @param check
     * @return
     * @param <T>
     */
    protected static <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return parser.call();
        } catch (Exception var4) {
            if (check.isAssignableFrom(var4.getClass())) {
                throw new JsonParseException(var4);
            }
            throw new IllegalStateException(var4);

        }
    }

    /**
     * 序列化
     *
     * @param obj
     * @return
     */
    public static String writeValueAsString(Object obj) {
        return JacksonUtil.tryParse( () ->{
            return JacksonUtil.getObjectMapper().writeValueAsString(obj);
        });
    }

    /**
     * 反序列化
     *
     * @param content
     * @param valueType
     * @param <T>
     * @return
     */
    public static <T> T readValue(String content, Class<T> valueType) {
        return JacksonUtil.tryParse(() ->{
           return JacksonUtil.getObjectMapper().readValue(content, valueType);
        });
    }

    /**
     * 反序列化List
     *
     * @param content
     * @param parameterClasses List内元素类型
     * @param <T>
     * @return
     */
    public static <T> T readListValue(String content, Class<?> parameterClasses) {

        JavaType javaType = JacksonUtil.getObjectMapper()
                .getTypeFactory()
                .constructParametricType(List.class, parameterClasses);

        return JacksonUtil.tryParse(() ->{
            return JacksonUtil.getObjectMapper().readValue(content, javaType);
        });
    }


}
